{% extends "../single_page.html" %}

{% block specific_page_css %}
  <style>
    button.button_group1+div+div {
        width: 200px;
        margin-top: 7px;
        margin-left: 1em;
        z-index: 1000;
    }
  </style>
{% endblock %}

{% block title %}
<title>样本库信息管理 样本信息</title>
{% endblock %}

{% block header_title %}
<h1>样本信息</h1>
{% endblock %}

{% block header_ol %}
    <li class="breadcrumb-item"><a href="/Home/">Home</a></li>
    <li class="breadcrumb-item">BIS</li>
    <li class="breadcrumb-item active">SampleInfo</li>
{% endblock %}

{% block page-script %}
<script>
  $(document).ready(function () {
      $("#sidebar_BIS>a").addClass("active");
      $("#sidebar_BIS").addClass("menu-open");
      $("#sidebar_BIS>ul>li:eq(1)>a").addClass("active");
      $(".sidebar").removeAttr("hidden");

      let model0 = "SampleInfo";
      let url0 = '/api/BIS/' + model0 + '/';
      let url1 = '/api/BIS/SampleInventoryInfo/';
      let id0 = 0;
      let bulk_update_bool = {% if perms.BIS.bulk_update_SampleInfo %} true {% else %} false {% endif %};
      let bulk_delete_bool = {% if perms.BIS.bulk_delete_SampleInfo %} true {% else %} false {% endif %};

      function update_func(e, id0){
          e.preventDefault();
          let sampler_id = $('#sampler_id').val();
          // 递交前检查，一般是检测model的外键是否存在
          let data1 = $.ajax({
              url: url1, dataType: 'json', contentType: "application/json",
              type: "get", async: false, data: {sampler_id: sampler_id, fields: "id"}
          }).responseJSON[0];
          if (data1 === undefined) {
              data1 = {
				  sampler_id: sampler_id, plasma_num: 0, cancer_tissue_num: 0, adjacent_mucosa_num: 0,
				  WBC_num: 0, stool_num: 0, memo: "无"
			  };
			  $.ajax({
				  url: url1,
				  method: 'POST',
				  async: false,
				  data: $.param(data1),
				  success: function () {
					  databaseRecordAjaxPut('{{ user.id }}', 'SampleInventoryInfo', "单项添加", "华大编号: " + sampler_id);
					  data1 = $.ajax({
						  url: url1, dataType: 'json', contentType: "application/json",
						  type: "get", async: false, data: { sampler_id: sampler_id, fields: "id"}
					  }).responseJSON[0];
				  },
				  error: function (jqXHR, textStatus, errorThrown) {
					  $('#myModalError').text('出现错误！！！请联系管理员');
					  console.info(">>>>url_ajax0:", url_ajax0);
					  console.info(">>>>method:", send_data0);
					  console.info(">>>>send_data0:", send_data0);
					  console.info(jqXHR,  textStatus, errorThrown);
				  }
			  });
              // $('#myModalError').text('错误！！！华大编号不存在，请填写正确的华大编号。');
              // return
          }

          let type = $('#type').val();
          let method = '';
          let url_ajax0 = url0;
          let send_data0 = $("#modelForm").find(":not(#sampler_id)").serialize() + '&' +
              $.param({ sampleinventoryinfo: data1.id });
          if (type === 'new') {
              // new
              method = 'POST';
              // POST前检查，一般是检测model的关键字段值是否存在
              data0 = $.ajax({
                  url: url0, dataType: 'json', contentType: "application/json",
                  type: "get", async: false, data: { sample_id: $('#sample_id').val(), fields: "id" }
              }).responseJSON[0];
              if (data0 !== undefined) {
                  $('#myModalError').text('错误！！！生物样本编号已存在，无法添加。如需更新该条目，请在对应行进行更新操作。');
                  return
              }
          } else {
              // edit
              url_ajax0 = url0 + id0 + '/';
              method = 'PUT';
          }

          $.ajax({
              url: url_ajax0,
              method: method,
              data: send_data0,
              headers: {'X-HTTP-Method-Override': 'PATCH'},
              success: function () {
                  let v_tmp = $('#sample_id').val();
                  if (type === 'new') {
                      databaseRecordAjaxPut('{{ user.id }}', model0, "单项添加", "生物样本编号：" + v_tmp);
                      $('#myModalError').text('添加成功！！！生物样本编号：' + v_tmp);
                  } else {
                      databaseRecordAjaxPut('{{ user.id }}', model0, "单项更新", "生物样本编号：" + v_tmp);
                      $('#myModalError').text('更新成功！！！生物样本编号：' + v_tmp);
                  }

                  setTimeout(
                      function () {
                          window.location.reload(true);
                      }, 3000
                  );
              },
              error: function (jqXHR, textStatus, errorThrown) {
                  $('#myModalError').text('出现错误！！！请联系管理员');
                  console.info(url_ajax0, method, send_data0);
                  console.log(jqXHR + ';' + textStatus + ';' + errorThrown);
              }
          });
      }

      let input_params = {
          "title1_text": "样本信息 总条目数： ",
          "fields": [
              //                    [   0,     1,        2,               3,       4,       5,       6 ]
              // input类型是select： [ field, name, 是否出现在modal, modal中排序, 是否必填, input类型, [[value, text]] ]
              // input类型不是select： [ field, name, 是否出现在modal, modal中排序, 是否必填, input类型, value ]
              ["sample_id", "生物样本编号", 1, 1, 1, "text"],
              ["sampler_id", "华大编号", 1, 0, 1, "text"],
              ["raw_id", "原始样本编号", 1, 2, 1, "text", "无"],
              ["fridge", "冰箱位置", 1, 3, 0, "text", "无"],
              ["plate", "孔板号", 1, 4, 0, "text", "无"],
              ["well", "孔位", 1, 5, 0, "text", "无"],
              ["sample_type", "样本类型", 1, 6, 0, "select", [["P", "血浆"], ["L", "癌组织"],["S", "癌旁组织"], ["B", "白细胞"], ["T", "粪便"]]],
              ["sample_date", "采样日期", 1, 7, 0, "date", "2000-01-01"],
              ["send_date", "寄送日期", 1, 8, 0, "date", "2000-01-01"],
              ["memo", "备注", 1, 9, 0, "text", "无"],
              ["last_modify_time", "上次修改时间", 0],
              ["create_time", "创建时间", 0]
          ],
          "update_func": update_func,
          "delete_func": simple_delete_func,
          "bulkDelete_func": simple_bulkDelete_func,
          "download_excel": '/ADVANCE/download_excel/BIS_' + model0 + '/'
      };
      single_page_generator(model0, url0, id0, bulk_update_bool, bulk_delete_bool, input_params);

      $("#sampler_id").blur(
          function () {
              $("#sample_id").val($("#sampler_id").val());
          }
      );
  });
</script>
{% endblock %}
